package com.hqd.ch03.v43.web.config;

import com.hqd.ch03.v43.config.BeanDefinition;
import com.hqd.ch03.v43.reader.xml.ParserContext;
import com.hqd.ch03.v43.reader.xml.parse.BeanDefinitionParser;
import com.hqd.ch03.v43.web.servlet.handler.RequestMappingHandlerMapping;
import com.hqd.ch03.v43.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.w3c.dom.Element;

public class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
    public static final String HANDLER_MAPPING_BEAN_NAME = RequestMappingHandlerMapping.class.getName();

    public static final String HANDLER_ADAPTER_BEAN_NAME = RequestMappingHandlerAdapter.class.getName();

    @Override
    public BeanDefinition parse(Element element, ParserContext context) {

        /**
         * 映射器BeanDefinition定义
         */
        BeanDefinition handlerMappingDef = new BeanDefinition(RequestMappingHandlerMapping.class);
        handlerMappingDef.getPropertyValues().add("order", 0);
        handlerMappingDef.setSingleton();
        if (element.hasAttribute("enable-matrix-variables")) {
            boolean enableMatrixVariables = Boolean.parseBoolean(element.getAttribute("enable-matrix-variables"));
            handlerMappingDef.getPropertyValues().add("removeSemicolonContent", !enableMatrixVariables);
        }

        context.getRegistry().registerBeanDefinition(HANDLER_MAPPING_BEAN_NAME, handlerMappingDef);

        /**
         * 适配器定义
         */
        BeanDefinition handlerAdapterDef = new BeanDefinition(RequestMappingHandlerAdapter.class);
        handlerAdapterDef.setSingleton();

        if (element.hasAttribute("ignore-default-model-on-redirect")) {
            Boolean ignoreDefaultModel = Boolean.valueOf(element.getAttribute("ignore-default-model-on-redirect"));
            handlerAdapterDef.getPropertyValues().add("ignoreDefaultModelOnRedirect", ignoreDefaultModel);
        }
        context.getRegistry().registerBeanDefinition(HANDLER_ADAPTER_BEAN_NAME, handlerAdapterDef);
        return null;
    }
}
